package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.itzb.asone.fileserver.IFileServer;
import com.itzb.asone.fileserver.model.FSResult;
import com.itzb.asone.utils.GitId;
import com.itzb.asone.utils.SpringContextUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;

public final class Base64Uploader {

	public static State save(HttpServletRequest request, Map<String, Object> conf) {
		
		IFileServer fileServer = SpringContextUtil.getBean("fileServer");
		
	    String filedName = (String) conf.get("fieldName");
		String file = request.getParameter(filedName);
		byte[] data = decode(file);

//		long maxSize = ((Long) conf.get("maxSize")).longValue();
//
//		if (!validSize(data, maxSize)) {
//			return new BaseState(false, AppInfo.MAX_SIZE);
//		}
//
//		String suffix = FileType.getSuffix("JPG");
//
//		String savePath = PathFormat.parse((String) conf.get("savePath"),
//				(String) conf.get("filename"));
//		
//		savePath = savePath + suffix;
//		String rootPath = ConfigManager.getRootPath(request,conf);
//		String physicalPath = rootPath + savePath;
//
//		State storageState = StorageManager.saveBinaryFile(data, physicalPath);

		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		String fileType = "JPG";
		String fileName = GitId.getFileName() + "." + fileType;
		File filePath = new File(realPath + "/" + fileName);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
			bos.write(data);
			bos.flush();
			bos.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		FSResult fsResult = fileServer.uploadFile(filePath.getPath(), fileName);
		
		State storageState = new BaseState(true);
		if (storageState.isSuccess()) {
			storageState.putInfo("url", PathFormat.format(fsResult.getList().get(0).getFilePath()));
			storageState.putInfo("type", fileType);
			storageState.putInfo("original", "");
		}

		return storageState;
	}

	private static byte[] decode(String content) {
		return Base64.decodeBase64(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}
	
}